package cn.hist.hfp.controller;

import cn.hist.hfp.RoleType;
import cn.hist.hfp.entity.Stray;
import cn.hist.hfp.service.StrayService;
import cn.hist.hfp.util.Authentication;
import cn.hist.hfp.util.MyResponse;
import cn.hist.hfp.vo.StrayVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/stray")
public class StrayController {

    private final
    StrayService strayService;

    private final
    Authentication authentication;

    @Autowired
    public StrayController(StrayService strayService, Authentication authentication) {
        this.strayService = strayService;
        this.authentication = authentication;
    }

    @PostMapping
    public int create(@RequestBody Stray stray, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.USER);
        Stray createdStray = strayService.create(stray);
        if (createdStray == null)
            return -1;
        return strayService.create(stray).getId();
    }

    @GetMapping("/{id}")
    public StrayVO findOne(@PathVariable int id) {
        return strayService.findOneVO(id);
    }

    @GetMapping("/page/{page}")
    public List<StrayVO> findSome(@PathVariable int page) {
        return strayService.findSome(page);
    }

    @GetMapping("/page")
    public int numberOfPages() {
        return strayService.numberOfPages();
    }

    @PutMapping
    public StrayVO update(@RequestBody Stray stray, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.USER);
        return strayService.update(stray);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Integer> delete(@PathVariable int id, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.USER, RoleType.MANAGER);
        return new MyResponse<Integer>().response(200, authentication.refreshToken(token), strayService.delete(id));
    }
}
